package com.sbtr.business.user.service.impl;

import com.sbtr.util.PageDtoUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.common.PageDto;
import com.sbtr.open.user.dto.UserInfoDto;
import com.sbtr.business.user.entity.UserInfo;
import com.sbtr.business.user.mapper.UserInfoMapper;
import com.sbtr.business.user.service.IUserInfoService;
import com.sbtr.util.BeanCopyUtils;

/**
 * <p>
 * 用户信息表，仅记录登录过系统的用户信息 服务实现类
 * </p>
 *

 */
@Transactional
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

	@Override
 	public UserInfoDto findById(Long id) {
		return BeanCopyUtils.copyProperties(getById(id), UserInfoDto.class);
	}

	@Override
 	public PageDto<UserInfoDto> search(String username,Long currPage,Long pageSize) {

		IPage<UserInfo> page = new Page<>();
		if(currPage != null){
			page.setCurrent(currPage);
		}
		if(pageSize != null){
			page.setSize(pageSize);
		}

		QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
		if(StringUtils.isNotEmpty(username)){
			wrapper.like("username", username);
		}
		wrapper.orderByDesc("id");

		page = page(page, wrapper);

		return PageDtoUtils.getPageDtoByIPage(page, UserInfoDto.class);
	}

	/**
	 * 异步方法<br />
	 * 若用户不存在则保存用户信息，否则直接返回，根据mip账号判断用户是否已存在
	 * @param userInfoDto
	 */
	@Override
 	@Async("asyncExecutor")
	public void saveIfAbsent(UserInfoDto userInfoDto){
		if(userInfoDto != null && StringUtils.isNotEmpty(userInfoDto.getUid())){
			QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
			wrapper.eq("uid", userInfoDto.getUid());
			if(getOne(wrapper) == null){
				save(BeanCopyUtils.copyProperties(userInfoDto, UserInfo.class));
			}
		}
	}

}
